<template>
  <div class="myOrder">
    <Card _Title="售后订单" :_Size="16"></Card>

    <!-- 搜索 筛选 -->
    <div class="search-box">
      <a-input-search :style="{width:'320px', background: '#ef4444'}" placeholder="请输入订单号搜索" v-model="apiParams.keywords" search-button class="input-search" @search="getList">
        <template #button-icon>
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 1024 1024"><path fill="currentColor" d="M1014.64 969.04L703.71 656.207c57.952-69.408 92.88-158.704 92.88-256.208c0-220.912-179.088-400-400-400s-400 179.088-400 400s179.088 400 400 400c100.368 0 192.048-37.056 262.288-98.144l310.496 312.448c12.496 12.497 32.769 12.497 45.265 0c12.48-12.496 12.48-32.752 0-45.263zM396.59 736.527c-185.856 0-336.528-150.672-336.528-336.528S210.734 63.471 396.59 63.471c185.856 0 336.528 150.672 336.528 336.528S582.446 736.527 396.59 736.527"/></svg>
        </template>
      </a-input-search>
    </div>
    <!--<a-spin :loading="loading" tip="加载中...">-->
    <div class="order-content">
      <div class="order-list" v-if="orderList && orderList.length" v-for="(order, onderIndex) in orderList" :key="onderIndex">
        <div class="order-header">
          <div>
            <div>
              <span class="order-status">{{ filterOrderStatus(order.serviceStatus) }}</span>
            </div>
            <div>售后单号：{{ order.sn }} &nbsp; &nbsp; &nbsp;{{order.createTime}}</div>
          </div>
          <div>
              <span v-if="order.orderStatus === 'COMPLETED'">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                  <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 6h18m-2 0v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6m3 0V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2m-6 5v6m4-6v6"/>
                </svg>
              </span>
            <span style="">申请退款金额：<span class="price-color">{{ unitPrice(order.flowPrice, "￥") }}</span></span>
          </div>
        </div>
        <div class="order-body">
          <div class="goods-list">
            <div>
              <img @click="goodsDetail(order.skuId, order.goodsId)" class="hover-color" :src="order.goodsImage" alt=""/>
              <div>
                <div class="hover-color" @click="goodsDetail(order.skuId, order.goodsId)">{{ order.goodsName }}</div>
                <div> x {{ order.num }}</div>
              </div>
            </div>
          </div>
          <div class="shop-list">
            <span @click="goShopPage(order.storeId)">{{ order.storeName }}</span>
          </div>
          <div class="order-options">
            <!-- 订单基础操作 -->
            <a-button @click="orderDetail(order.sn)" size="mini" type="primary" status="warning">售后详情</a-button>
            <a-button @click="handleReceived(order.sn)" size="mini" type="outline" status="warning" v-if="order.serviceStatus == 'PASS' &&order.serviceType != 'RETURN_MONEY'">提交物流</a-button>
            <a-button @click="handleCancel(order.sn)" size="mini" type="primary" status="danger" v-if="order.afterSaleAllowOperationVO.cancel">取消售后</a-button>
          </div>
        </div>
      </div>
      <Empty v-else />
    </div>
    <!--</a-spin>-->

    <!-- 分页 -->
    <div class="paginationBox">
      <a-pagination :total="total" :current="apiParams.pageNumber" :page-size="apiParams.pageSize" show-page-size
                    @change="(number) => {apiParams.pageNumber = number;}" @page-size-change="(number) => {apiParams.pageSize = number; apiParams.pageNumber = 1;}" >
      </a-pagination>
    </div>

    <!--提交物流信息-->
    <a-modal v-model:visible="logisticsModal" width="600px" top="100">
      <template #title>提交物流信息</template>
      <a-form ref="logisticsRef" :model="logisticsForm" size="large" layout="horizontal" auto-label-width :style="{ width: '400px'}" class="mt_20">
        <a-form-item field="logisticsId" label="物流公司" :rules="[REQUIRED]">
          <a-select :style="{width:'320px'}" placeholder="" v-model="logisticsForm.logisticsId">
            <a-option v-for="item in companyList" :value="item.id" :key="item.id">{{item.name}}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="logisticsNo" label="物流单号" :rules="[REQUIRED]">
          <a-input v-model="logisticsForm.logisticsNo" allow-clear placeholder="请填写物流单号" :style="{width:'320px'}"></a-input>
        </a-form-item>
        <a-form-item field="mDeliverTime" label="发货时间" :rules="[REQUIRED]">
          <a-date-picker type="date" v-model="logisticsForm.mDeliverTime" placeholder="请选择发货时间" :style="{width:'320px'}" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="logisticsModal = false">取消</a-button>
        <a-button @click="handleSubmit" status="danger" type="primary" :loading="loading">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, onMounted, watch } from 'vue';
  import { afterSaleStatusList } from '../enumeration.js';
  import { unitPrice } from '@/utils/filters';
  import { REQUIRED } from '@/utils/validator';
  import { Message, Modal } from '@arco-design/web-vue';
  import { afterSaleList, cancelAfterSale } from '@/api/member';
  import { afterSaleDelivery, getLogisticsCompany } from '@/api/order';

  const router = useRouter();
  // 请求参数
  const apiParams = ref({
    pageNumber: 1,
    pageSize: 10,
    keywords: '',
    sn: '',
    sort: 'createTime',
    order: 'desc',
  });
  const orderList = ref<Array<any>>([]);
  const total = ref(0);
  const loading = ref(false);
  const logisticsModal = ref(false);  // 提交物流信息modal
  const logisticsRef = ref(); // 物流信息表单ref
  const logisticsForm = ref({
    afterSaleSn: '',
    logisticsId: '',
    logisticsNo: '',
    mDeliverTime: ''
  }); // 物流信息表单
  const companyList = ref(); // 物流公司列表

  // 获取订单列表
  const getList = () => {
    let params = JSON.parse(JSON.stringify(apiParams.value));
    loading.value = true;
    afterSaleList(params).then(res => {
      loading.value = false;
      if (res.data.success) {
        orderList.value = res.data.result.records;
        total.value = res.data.result.total;
      }
    });
  };

  // 跳转商品详情
  const goodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };
  // 跳转店铺首页
  const goShopPage = (id: any) => {
    let routeUrl = router.resolve({path: "/merchant", query: { id },});
    window.open(routeUrl.href, "_blank");
  };
  // 订单详情
  const orderDetail = (sn: any) => {
    router.push({ path: `/user/home/orderCenter/afterSaleDetail`, query: { sn } });
  };
  // 获取物流公司列表
  const getCompany = () => {
    getLogisticsCompany().then(res => {
      if (res.data.success) {
        companyList.value = res.data.result;
      }
    })
  };
  // 提交物流
  const handleReceived = (sn: any) => {
    logisticsForm.value.afterSaleSn = sn;
    logisticsModal.value = true;
    if (!companyList.value || !companyList.value.length) {
      getCompany();
    }
  };
  // 提交物流信息
  const handleSubmit = async () => {
    const auth = await logisticsRef.value?.validate();
    if (!auth) {
      loading.value = true;
      afterSaleDelivery(logisticsForm.value).then(res => {
        if (res.data.success) {
          logisticsModal.value = false;
          Message.success('提交成功');
          getList();
        }
        loading.value = false;
      }).catch(() => {
        loading.value = false;
      })
    }
  };
  // 取消售后
  const handleCancel = (sn: any) => {
    Modal.confirm({
      title: '取消售后',
      content: `确定取消此次售后申请吗？`,
      okButtonProps: {
        type: "primary",
        status: "danger"
      },
      onOk: () => {
        cancelAfterSale(sn).then(res => {
          if (res.data.success) {
            Message.success('取消售后申请成功');
            getList();
          }
        })
      }
    })

  };

  const filterOrderStatus = (status: any) => { // 获取订单状态中文
    const ob = afterSaleStatusList.filter(e => { return e.status === status });
    return ob && ob[0] ? ob[0].name : status
  };

  onMounted(() => {
    getList();
  });

  watch(() => [apiParams],
    (val: any) => {
      getList();
    }, { deep: true }
  );
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-direction: row-reverse;
  }


  .order-content {
    width: 100%;
    margin: 20px 0;
    .order-list {
      border: 1px solid #ddd;
      border-radius: 3px;
      margin-bottom: 10px;
      .order-header {
        display: flex;
        align-items: center;
        padding: 10px;
        justify-content: space-between;
        border-bottom: 1px solid #ddd;
        > div:nth-child(1) > div:nth-child(1) > .order-status {
          display: inline-block;
          /*width: 70px;*/
        }
        > div:nth-child(1) > div:nth-child(2) {
          font-size: 12px;
          color: #999;
          margin-top: 6px;
        }
        > div:nth-child(2) {
          display: flex;
          align-items: flex-end;
        }
        > div:nth-child(2) > span:nth-child(2) {
          margin-bottom: 1px;
          display: inline-block;
          margin-left: 10px;
        }
      }
      .order-body {
        display: flex;
        justify-content: space-between;
        color: #999;
        padding: 10px;
        .goods-list {
          width: 580px;
        }
        .goods-list > div {
          width: 500px;
          display: flex;
          margin-bottom: 10px;
          img {
            width: 60px;
            height: 60px;
            margin-right: 10px;
          }
          > div {
            flex: 1;
            > div:nth-of-type(2) {
              margin-top: 10px;
            }
          }
        }
        .shop-list {
          span {
            color: @link_color;
            cursor: pointer;
            font-size: 12px;
          }
        }
        .order-options {
          display: flex;
          flex-direction: column;
          .arco-btn {
            margin-bottom: 6px;
          }
        }
      }
    }
  }
</style>
